# -*- coding:utf-8 -*-
import time

from fastapi import FastAPI, APIRouter
from fastapi import Request, HTTPException
from fastapi.exceptions import RequestValidationError
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware

from domain.response.BaseResponse import UnicornException
from domain.response.http_error import http_error_handler, unicorn_exception_handler
from domain.response.validation_error import http422_error_handler
from webapp.settings.configs import MWA_ORIGINS, MWA_ALLOW_CREDENTIALS, MWA_ALLOW_METHODS, MWA_ALLOW_HEADERS
from webapp.routers import index

API_HOST, API_PORT = '0.0.0.0', 80

webapp = FastAPI()

# Log
# webapp.state.log = LoggerFactory('log').logger

# 添加事件
# webapp.add_event_handler("startup", create_start_app_handler(application))
# webapp.add_event_handler("shutdown", create_stop_app_handler(application))

# 添加错误处理
webapp.add_exception_handler(HTTPException, http_error_handler)
webapp.add_exception_handler(RequestValidationError, http422_error_handler)
webapp.add_exception_handler(UnicornException, unicorn_exception_handler)

# 中间件
webapp.add_middleware(GZipMiddleware, minimum_size=1000)

# 解决跨域问题
webapp.add_middleware(
    CORSMiddleware,
    allow_origins=MWA_ORIGINS,
    allow_credentials=MWA_ALLOW_CREDENTIALS,
    allow_methods=MWA_ALLOW_METHODS,
    allow_headers=MWA_ALLOW_HEADERS,
)


# 中间件
@webapp.middleware("http")
async def test(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


@webapp.get('/favicon.ico')
def get_favicon():
    return None


# 路由
router = APIRouter()
webapp.include_router(index.router)

# 挂载静态文件目录
# webapp.mount('/', StaticFiles(directory=STATIC_DIR), name="public")
# webapp.mount('/template', StaticFiles(directory=TEMPLATE_DIR), name="template")

# webapp.render = Jinja2Templates(directory=template.TEMPLATE_DIR)
